package com.easy.dn.ui.mainFragment;

import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.easy.common.baserx.RxSubscriber;
import com.easy.common.commonwidget.CustomPopWindow;
import com.easy.dn.api.Api;
import com.easy.dn.api.ApiService;
import com.easy.dn.bean.ResumeChat;
import com.easy.dn.ui.main.activity.ChatActivity;
import com.easy.dn.utils.MapHelper;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.easeui.widget.EaseTitleBar;
import com.kyleduo.switchbutton.SwitchButton;

import java.util.HashMap;
import java.util.Map;

import dn.easy.com.easyto.R;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 丁宁
 * on 2017/5/2.
 * 聊天
 */

public class ChatFragment extends EaseConversationListFragment {
    private EaseTitleBar mTitleBar;
    private CustomPopWindow mCustomPopWindow;
    private SwitchButton mChatTurn;
    private String mUsername;
    private boolean isChatState = false;
    private boolean isALlChatState = false;
    //    @Override
//    protected int getLayoutResource() {
//        return R.layout.fra_chat;
//    }
//
//    @Override
//    public void initPresenter() {
//
//    }
//
//    @Override
//    protected void initView() {
//
//    }

    @Override
    protected void initView() {
        super.initView();
        View errorView = (LinearLayout) View.inflate(getActivity(), R.layout.fra_chat, null);
        mTitleBar = (EaseTitleBar) getView().findViewById(R.id.title_bar);

        mTitleBar.setRightImageResource(R.drawable.resume_detail_more_icon);
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopTopWithDarkBg();
            }

        });
//        loadSwitchState();
    }

    private void loadSwitchState() {
        Map<String, String> map = new HashMap<String, String>();
        Api.getInstance().getProxy(ApiService.class).getIsAllChat(Api.getCacheControl(), map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<ResumeChat>(getActivity(), false) {
                    @Override
                    protected void _onNext(ResumeChat resumeChat) {
                        if (resumeChat.isReject()) {
                            isALlChatState = true;
                        } else
                            isALlChatState = false;
                    }
                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        // register context menu
        registerForContextMenu(conversationListView);
        conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation conversation = conversationListView.getItem(position);
                // 发送请求判断对方是否接受消息
                if (conversation != null) {
                    mUsername = conversation.conversationId();
                    Log.i("DNLOG",mUsername);
                    loadChatState();
                }

            }
        });
        super.setUpView();
        //end of red packet code
    }

    private void loadChatState() {
        Map<String, String> map = MapHelper.getAccessMap();
        map.put("userIMName", mUsername);
        Api.getInstance().getProxy(ApiService.class).getIsChat(Api.getCacheControl(), map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<ResumeChat>(getActivity(), true) {
                    @Override
                    protected void _onNext(ResumeChat resumeChat) {
                        if (resumeChat.isReject()) {
                            isChatState = true;
                        } else
                            isChatState = false;
                        Intent intent = new Intent(getActivity(), ChatActivity.class);
                        intent.putExtra("userIsChecked", isChatState);
                        intent.putExtra(EaseConstant.EXTRA_USER_ID, mUsername);
                        startActivity(intent);
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    /**
     * 显示PopupWindow 同时背景变暗
     */
    private void showPopTopWithDarkBg() {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_im_menu, null);

        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        //弹出popWindow时，背景是否变暗
        // 控制亮度
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setView(contentView)
                .setAnimationStyle(R.style.CustomPopWindowStyle)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.5f) // 控制亮度
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        Log.e("TAG", "onDismiss");
                    }
                })
                .create()
                .showAsDropDown(mTitleBar.getRightLayout(), 10, 30);

    }

    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView) {

        mChatTurn = (SwitchButton) contentView.findViewById(R.id.sb_chat_turn);
        mChatTurn.setChecked(isALlChatState);
        mChatTurn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                if (b) {
//                    //禁止聊天
//
//                } else {
//                    //打开聊天
//                }
//                changeSwitchState(b);
            }
        });
    }

    private void changeSwitchState(boolean b) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("userIMName", "");
        map.put("type", b+"");
        Api.getInstance().getProxy(ApiService.class).setIsAllChat(Api.getCacheControl(), map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<ResumeChat>(getActivity(), false) {
                    @Override
                    protected void _onNext(ResumeChat resumeChat) {
                        if (mCustomPopWindow!=null){
                            mCustomPopWindow.dissmiss();
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

}
